/**
 * 
 */
package com.baijia.tianxiao.connect.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.baijia.tianxiao.connect.result.BaseApiResult;
import com.baijia.tianxiao.connect.util.TianxiaoConnectUtil;

/**
 * @author leiruiqi
 *
 * 发送消息
 * 
 */
@RequestMapping("/sendMessage")
@RestController
public class SendMessageController {
	private static Logger logger = LoggerFactory.getLogger(SendMessageController.class); 
    
	@RequestMapping("/sendSingle")
	public BaseApiResult sendBySessionKey(HttpServletRequest request,String sessionKey,String message) {
		BaseApiResult result = new BaseApiResult();
		if(sessionKey == null){
			sessionKey = request.getParameter("sessionKey");
		}
		if(message == null){
			message = request.getParameter("message");
		}
		WebSocketSession session = TianxiaoConnectUtil.getSession(sessionKey);
		if(session == null){
			result.setCode("-1");
			result.setMsg("not online");
			
			return result;
		}
		
		TextMessage textMessage = new TextMessage(message);
		
		boolean bool = TianxiaoConnectUtil.sendMessage(session, textMessage);
		
		if(!bool){
			result.setCode("-1");
			result.setMsg("send message exception");	
		}
		
		return result;
	}
	
	@RequestMapping("/sendBatch")
	public BaseApiResult sendBatchBySessionKey(HttpServletRequest request,String sessionKeys,String message) {
		BaseApiResult result = new BaseApiResult();
		if(sessionKeys == null){
			sessionKeys = request.getParameter("sessionKeys");
		}
		if(message == null){
			message = request.getParameter("message");
		}
		String[] sessionKeysStr = sessionKeys.split(",");
		for(String sessionKey : sessionKeysStr){
			
			WebSocketSession session = TianxiaoConnectUtil.getSession(sessionKey);
			if(session == null){
				continue;
			}
			
			TextMessage textMessage = new TextMessage(message);
			
			TianxiaoConnectUtil.sendMessage(session, textMessage);
			
		}
		return result;
	}
	
}
